const router = require('koa-router')()
const Store = require('../models/store')
const User = require('../models/user')
const Order = require('../models/order')
const Money = require('../models/money')
let nanoid = require('nanoid')

/**
 * 创建商店
 * @type {[type]}
 */
router.post('/onloadstore', async (ctx, next) => {
    try {
        let {openid, name, address, feature, pic, bankId, bankName,bindBankName, tel} = ctx.request.body
        await User.update({openid}, {$set: {bankId, bankName, bindBankName, phone: tel}}, {upsert: true})
        let u = await User.findOne({openid})
        let s = await Store.findOne({storied: `${nanoid().slice(0,10)}${u.phone}`})
        if (!s) { // todo 创建商店
            s = await Store.create({
                openid: openid,
                name: name,
                address: address,
                feature: feature,
                tel: u.phone,
                pic,
                storied: `${nanoid().slice(0,10)}${u.phone}`,
                wallet: 0
            })
            ctx.body = {
                code: 0,
                data: {storied: s.storied, name: s.name, address: s.address, tel: s.tel, pic: s.pic, storied:s.storied, consumerqueue: s.consumerqueue}
            }
        } else {
            ctx.body = {
                code: -1,
                errmsg: `${name} 已存在，请先去修改店名`
            }
        }
    } catch (err) {
        ctx.body = {
            code: -1,
            errmsg: `error :${err}`
        }
    }
})

/**
 * 商户(开始页面)
 * @type {[type]}
 */
router.post('/begin', async (ctx, next) => {
    try {
        let {
            openid,
            nickname = '',
            bankId = '',
            phone = '',
            mail = ''
        } = ctx.request.body
        let u = await User.findOne({openid})
        if (!u) {
            await User.create({openid, nickname, bankId, phone, mail})
        }

        let ret = await Store.find({openid})
        let arr = ret.map(item => {
            return {storeid: item.storied, name: item.name}
        })
        ctx.body = {
            code: 0,
            data: arr
        }

    } catch (err) {
        ctx.body = {
            code: -1,
            errmsg: `error: ${err}`
        }
    }
})

/**
 * 获取商户信息通过storied
 * @type {[type]}
 */
router.get('/getStreInfo', async (ctx, next) => {
    try {
        let {storied} = ctx.query
        let s = await Store.findOne({storied}).select('-_id -openid -updatedAt ')
        ctx.body = {
            code: 0,
            data: s
        }
    } catch (err) {
        ctx.body = {
            code: -1,
            errmsg: `error: ${err}`
        }
    }
})

/**
 * 获取排名
 * @type {[type]}
 */
router.get('/ranking', async (ctx, next) => {
    try {
        let count = 10
        let ret = await Store.find({}).sort({sum: -1}).limit(count).select('-consumerqueue -_id -openid -createdAt -updatedAt')
        ctx.body = {
            code: 0,
            data: ret
        }
    } catch (err) {
        ctx.body = {
            code: -1,
            errmsg: `error: ${err}`
        }
    }
})

/**
 * 获取我的账单
 * @type {[type]}
 */
router.get('/myorder', async (ctx, next) => {
    try {
        let {openid} = ctx.query
        let ret = await Order.find({openid, status: true}).select('-_id -createdAt -updatedAt')
        ctx.body = {
            code: 0,
            data: ret
        }
    } catch (err) {
        ctx.body = {
            code: -1,
            errmsg: `error: ${err}`
        }
    }
})

/**
 * 修改让利
 * @type {Object}
 */
router.post('/modifyStoreInfo_t', async (ctx, next) => {
    try {
        let {storied, t} = ctx.request.body
        t = t/100
        await Store.update({
            storied
        }, {
            $set: {
                t
            }
        })
        ctx.body = {
            code: 0,
            data: `modify successful`
        }
    } catch (err) {
        ctx.body = {
            code: -1,
            errmsg: `error:${err}`
        }
    }
})

/**
 * 添加商品 (待修改)
 * @type {Object}
 */
router.post('/addGodds', async (ctx, next) => {
    try {
        let {name, price, id, storied} = ctx.request.body
        let s = await Store.findOne({storied})
        let arr = s.goodlist
        arr.push({name, price, src: id})
        await Store.update({
            storied
        }, {
            $set: {
                goodlist: arr
            }
        })
        ctx.body = {
            code: 0,
            data: `add successful`
        }
    } catch (err) {
        ctx.body = {
            code: -1,
            errmsg: `error: ${err}`
        }
    }
})

router.post('/pay', async (ctx, next) => {
    try {
        let {openid, storied, cost, nickname=''} = ctx.request.body
        cost = +cost
        let u = await User.findOne({openid})
        let store = await Store.findOne({storied})
        if (!u) {
            await User.create({openid, nickname})
        }
        //todo 查询商店的信息

        //todo 创建消费账单
        let o = await Order.create({
            openid,
            nickname,
            storied,
            cost,
            StoreName: store.name,
            pic: store.pic
        })
        ctx.body = {
            code: 0,
            data: {orderId: o._id}
        }
    } catch (err) {
        ctx.body = {
            code: -1,
            errmsg: `error:${err}`
        }
    }
})

/**
 * 修改打钱状态
 * @type {Object}
 */
router.post('/updateMoney', async (ctx, next) => {
    try {
        let {id} = ctx.request.body
        await Money.update({
            _id:id
        }, {
            $set: {
                status: false
            }
        })
        ctx.body = {
            code: 0,
            data: `update sucesss`
        }
    } catch (err) {
        ctx.body = {
            code: -1,
            errmsg: `error: ${err}`
        }
    }
})

/**
 * 获取需要打钱的列表
 * @type {[type]}
 */
router.get('/getMoneyList', async (ctx, next) => {
    try {
        let list = await Money.find({status: true}).select('-createdAt -updatedAt -status')
        let arr = []
        for(let i =0 ;i< list.length; i++) {
          let item = list[i]
          let u = await User.findOne({openid: item.openid})
          arr.push({
            openid: item.openid,
            cost: item.cost,
            bankId: u.bankId,
            bankName: u.bankName,
            bindBankName: u.bindBankName,
            phone: u.phone,
            mail: u.mail,
            _id: item._id
          })
        }

        ctx.body = {
            code: 0,
            data: arr
        }
    } catch (err) {
        ctx.body = {
            code: -1,
            errmsg: `error: ${err}`
        }
    }
})

/**
 * 支付成功修改账单的状态
 * @type {[type]}
 */
router.post('/paySuccess', async (ctx, next) => {
  try {
    let {orderId} = ctx.request.body
    let o = await Order.findOne({_id: orderId})
    await Order.update({_id: orderId} ,{$set: {status: true}})

    let store = await Store.findOne({storied: o.storied})

    let consumerqueue = store.consumerqueue
    let num = store.num + 1
    let cache = store.cache + o.cost * store.t*0.9 //t是让利比例
    let proxyPerson = store.proxyPerson + o.cost*store.t*0.04  //代理的钱
    let sum = parseFloat(store.sum) + parseFloat(o.cost)
    let wallet = parseFloat(store.wallet) + parseFloat(o.cost)*(1 -store.t) * 0.99

    //info 存储消费的人和消费金额
    consumerqueue.push({
      openid: o.openid,
      nickname: o.nickname,
      cost: o.cost
    })

    let firstCustomer = consumerqueue[0] // 第一个消费的顾客的信息
    if (consumerqueue.length> 0 && cache >= firstCustomer.cost) {
        let sendCustomerMoney = firstCustomer.cost
        await Money.create({openid:o.openid, cost: sendCustomerMoney}) // 当cache超过第一个顾客的消费金额的时候,把第一个顾客的信息放到money表，同时把第一个顾客从consumerqueue去掉
        consumerqueue.shift()
        cache -= firstCustomer.cost
    }

    await Store.update({
        _id: store._id
    }, {
        $set: {
            consumerqueue,
            proxyPerson,
            num,
            cache,
            sum: sum,
            wallet
        }
    })

    let d = await Store.findOne({storied: store.storied})

    ctx.body = {code: 0, data: `successful`}
  }catch(err) {
    ctx.body = {code: -1, errmsg: `error:${err}`}
  }
})

/**
 * 添加银行信息
 * @type {Object}
 */
router.post('/addBankInfo', async (ctx, next) => {
  try {
    let {openid, bankId, bankName, bindBankName} = ctx.request.body
    await User.update({openid}, {$set: {bankId, bankName, bindBankName}})
    ctx.body = {code: 0, data: `add bank successful`}
  }catch(err) {
    ctx.body = {code: -1, errmsg: `error: ${err}`}
  }
})

/**
 * 获取商户的余额
 * @type {[type]}
 */
router.get('/getStoreWallet', async (ctx, next) => {
  try {
    let {storied} = ctx.query
    let store = await Store.findOne({storied})
    let user = await User.findOne({openid: store.openid})
    let obj = {
      bankId: user.bankId,
      bankName: user.bankName,
      bindBankName: user.bindBankName,
      phone: user.phone,
      mail: user.mail,
      wallet: store.wallet,
      proxyPerson: store.proxyPerson
    }
    ctx.body = {code: 0, data: obj}
  }catch(err) {
    ctx.body = {code: -1, errmsg: `error: ${err}`}
  }
})

/**
 * 打钱给代理
 * @type {[type]}
 */
router.post('/updateStoreProxy', async (ctx, next) => {
  try {
    let {storied, money} = ctx.request.body
    let store = await Store.findOne({storied})
    if (parseFloat(money) > store.proxyPerson) {
      ctx.body = {code: -1, errmsg: `您的余额只有:${money} 元`}
    }else {
      let num = store.proxyPerson - parseFloat(money)
      await Store.update({storied}, {$set: {proxyPerson: num}})
      ctx.body = {code: 0, data: `打钱给代理成功`}
    }
  }catch(err) {
    ctx.body = {code: -1, errmsg: `error: ${err}`}
  }
})

/**
 * 更新商户的余额
 * @type {[type]}
 */
router.post('/updateStoreWallet', async (ctx, next) => {
  try {
    let {storied, money} = ctx.request.body
    let store = await Store.findOne({storied})
    if (parseFloat(money) > store.wallet) {
      ctx.body = {code: -1, errmsg: `您的余额只有:${money} 元`}
    }else {
      let num = store.wallet - parseFloat(money)
      await Store.update({storied}, {$set: {wallet: num}})
      ctx.body = {code: 0, data: `打钱成功`}
    }
  }catch(err) {
    ctx.body = {code: -1, errmsg: `error: ${err}`}
  }
})


/**
 * 获取商店列表
 * @type {[type]}
 */
router.get('/getStoreList', async (ctx, next) => {
  try {
    let list = await Store.find().select('-t -sum -num -cache -wallet -consumerqueue -tel -goodlist -location')
    ctx.body = {
      code: 0, data: list
    }
  }catch(err) {
    ctx.body = {code: -1, errmsg: `error: ${err}`}
  }
})
module.exports = router
